<template>
  <div class="mainua">
    <div class="main_spac1" style="padding-bottom: 5px">
      <div class="main_white padding10">
        <div class="main_crumbs boxdq">
          <div class="main_crumbs_l">
            <a href="javascript:;" @click="$router.back(-1)">
              <i class="el-icon-arrow-down"></i>返回
            </a>
            <em>|</em>
            <span>{{ title }}</span>
          </div>
        </div>
        <div class="main_tile boxdq marginTop10">
          <div class="main_tile_l"><em></em>基本信息</div>
        </div>
        <div class="maincla_form">
          <el-form
            :inline="true"
            :model="form"
            ref="form"
            label-width="110px"
            :rules="rules"
          >
            <div>
              <el-form-item
                :label="
                  documentType == 3 || documentType == 4
                    ? '客户类型'
                    : '所属菜单'
                "
                prop="menu"
              >
                <el-cascader
                  :options="menuList"
                  :props="props"
                  class="wid240"
                  v-model="menuIds"
                  @change="selectAction($event, 'menu')"
                ></el-cascader>
              </el-form-item>
              <div class="clearfix"></div>
              <el-form-item label="标题" prop="title">
                <el-input
                  v-model="form.title"
                  placeholder="标题"
                  class="wid240"
                ></el-input>
              </el-form-item>
              <div class="clearfix"></div>
              <el-form-item
                v-if="documentType == 3"
                label="版本号"
                prop="version"
              >
                <el-input
                  v-model="form.version"
                  placeholder="版本号"
                  class="wid240"
                ></el-input>
              </el-form-item>
              <div class="clearfix"></div>
              <el-form-item v-if="documentType != 4" label="作者" prop="author">
                <el-input
                  v-model="form.author"
                  placeholder="作者"
                  class="wid240"
                ></el-input>
              </el-form-item>
              <div class="clearfix"></div>
              <el-form-item
                v-if="documentType != 4"
                label="发布"
                prop="status"
                class="wid240"
              >
                <el-switch
                  v-model="form.status"
                  active-color="#03A98E"
                  :active-value="1"
                  :inactive-value="0"
                ></el-switch>
              </el-form-item>
            </div>
            <div class="main_tile boxdq">
              <div class="main_tile_l">
                <em></em>内容
                <!-- <span>建议图片尺寸是:302*302，最多三张，主图为默认第一张</span> -->
              </div>
            </div>
            <div class="maincla_ed">
              <Editor
                apiKey="vl7byj8kh7hyvvi6o7137s7khcpfsp762987dlnbcd93u37a"
                v-model="form.content"
                :init="init"
              ></Editor>
            </div>
            <!-- <div class="err" v-show="showerr">请输入内容</div> -->
            <div class="clearfix"></div>
            <div class="newConBox_p200 paddingBottom10" id="newConBox">
              <div class="newConBox_h32">
                <div :class="['boxdq newConBox ', { on: searchBarFixed }]">
                  <div class="mainor_prl">
                    <el-button
                      v-if="!id"
                      type="primary"
                      @click="submitAction(1)"
                      v-repeatClick
                      >保存并继续添加</el-button
                    >
                    <el-button
                      class="reset marginLeft10"
                      type="primary"
                      @click="submitAction(2)"
                      v-repeatClick
                      >保存并返回列表</el-button
                    >
                  </div>
                </div>
              </div>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Editor from "@tinymce/tinymce-vue";
import init from "./init";
import { uploadPath } from "@/api/currency";
import {
  companyManualBaseData,
  addCompanyManual,
  companyManualDetail,
  editCompanyManual,
  addSiteNotice,
} from "@/api/document/document";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { recursion, category } from "@/utils/index";

export default {
  components: {
    Editor,
  },
  data() {
    var checkMenu = (rule, value, callback) => {
      if (this.menuIds.length > 0) {
        // if (this.documentType == 1 || this.documentType == 2) {
        // 	if (this.menuIds.length == 4 || this.menuIds[2] == 0) {
        // 		callback();
        // 	} else {
        // 		return callback(new Error("请选到最后一级"));
        // 	}
        // } else if (this.documentType == 3) {
        // 	if (this.menuIds.length == 2) {
        // 		callback();
        // 	} else {
        // 		return callback(new Error("请选到最后一级"));
        // 	}
        // }else{
        callback();
        // }
      } else {
        if (this.documentType == 3 || this.documentType == 4) {
          return callback(new Error("请选择客户类型"));
        } else {
          return callback(new Error("请选择所属菜单"));
        }
      }
    };
    return {
      id: null,
      documentType: 1, //类型：1：用户手册，2：常见问题 3.更新记录 4.站内通知
      title: "新增手册", //头部标题
      menuList: [], //菜单列表
      menuIds: [], //所属菜单
      init, // 富文本
      rules: {
        menu: [{ validator: checkMenu, required: true, trigger: "change" }],
        title: [{ required: true, message: "输入标题", trigger: "blur" }],
        author: [{ required: true, message: "输入作者", trigger: "blur" }],
      },
      form: {
        title: "",
        author: "",
        version: "",
      },
      uploadPath,
      props: {
        children: "selfNext",
        label: "name",
        value: "id",
        expandTrigger: "hover",
      },
      showerr: false,
      info: {}, // 信息

      searchBarFixed: false, // 监听滚动
    };
  },
  mounted() {
    this.id = this.$route.query.id;
    this.documentType = this.$route.query.type;
    this.getMenuList(this.documentType); //获取菜单列表

    let aoe = "新增",
      tit = "";
    if (this.id) {
      this.getDetail(this.id);
      aoe = "编辑";
    }
    switch (this.documentType) {
      case 1: {
        tit = "用户手册";
        break;
      }
      case 2: {
        tit = "常见问题";
        break;
      }
      case 3: {
        tit = "更新记录";
        Object.assign(this.rules, {
          version: [
            { required: true, message: "请输入版本号", trigger: "blur" },
          ],
        });
        break;
      }
      case 4: {
        tit = "站内通知";
        this.form = {
          title: "",
          content: "",
          status: 1, //默认传1
        };
        break;
      }
    }
    this.title = aoe + tit;
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  methods: {
    getMenuList(type) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name
      );
      companyManualBaseData(data).then((res) => {
        if (res.errcode == 0) {
          let data = res.data.company_menu_list;
          if (type == 3) {
            this.menuList = data.map((item) => {
              return {
                id: item.id,
                name: item.name,
                selfNext: item.selfNext.map((i) => {
                  return {
                    id: i.id,
                    name: i.name,
                    company_type: i.company_type,
                  };
                }),
              };
            });
          } else if (type == 4) {
            this.menuList = data.map((item) => {
              return {
                id: item.id,
                name: item.name,
              };
            });
          } else {
            this.menuList = data;
          }
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    getDetail(id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id }
      );
      companyManualDetail(data).then((res) => {
        if (res.errcode == 0) {
          let data = res.data.info;
          this.form.title = data.title;
          this.form.author = data.author;
          this.form.content = data.content;
          this.form.status = data.status;
          data.version ? (this.form.version = data.version) : null;
          this.menuIds = [data.type];
          data.product_type > 0 ? this.menuIds.push(data.product_type) : null;

          /* 
          gxm,修改,当为文档为更新记录时，menuIds不Push  first_menu_id,不知道会不会有错 */
          if (this.documentType != 3) {
            data.first_menu_id >= 0
              ? this.menuIds.push(data.first_menu_id)
              : null;
          }

          data.sec_menu_id > 0 ? this.menuIds.push(data.sec_menu_id) : null;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    selectAction(e, type) {},
    submitAction(btn) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          var formData = JSON.parse(JSON.stringify(this.form));
          formData.document_type = this.documentType;
          formData.type = this.menuIds[0];
          this.menuIds[1] ? (formData.product_type = this.menuIds[1]) : null;
          this.menuIds[2] >= 0
            ? (formData.first_menu_id = this.menuIds[2])
            : null;
          // this.menuIds[3] ? formData.sec_menu_id  = this.menuIds[3] : null;
          // formData.first_menu_id = this.menuIds[1] ? this.menuIds[1] :'0';
          formData.sec_menu_id = this.menuIds[3] ? this.menuIds[3] : -1;
          if (this.id) {
            formData.id = this.id;
          }
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name, formData)) +
                  apiUrl().appsecret
              ),
            },
            apiUrl().name,
            formData
          );
          if (this.documentType != 4) {
            if (this.id) {
              //编辑
              editCompanyManual(data).then((res) => {
                if (res.errcode == 0) {
                  this.$message({
                    message: "编辑成功",
                    type: "success",
                  });
                  // this.$router.go(-1);
                } else {
                  this.$message.error(res.errmsg);
                }
              });
            } else {
              //新增
              addCompanyManual(data).then((res) => {
                if (res.errcode == 0) {
                  this.$message({
                    message: "添加成功",
                    type: "success",
                  });
                  if (btn == 1) {
                    this.menuIds = [];
                    this.$refs.form.resetFields();
                  } else {
                    this.$router.go(-1);
                  }
                } else {
                  this.$message.error(res.errmsg);
                }
              });
            }
          } else {
            console.log(111);
            //站内通知
            addSiteNotice(data).then((res) => {
              if (res.errcode == 0) {
                this.$message({
                  message: "添加成功",
                  type: "success",
                });
                if (btn == 1) {
                  this.menuIds = [];
                  this.$refs.form.resetFields();
                } else {
                  this.$router.go(-1);
                }
              } else {
                this.$message.error(res.errmsg);
              }
            });
          }
        }
      });
    },
    // 监听滚动
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop + document.documentElement.clientHeight >
      document.getElementById("newConBox").offsetTop + 300
        ? (this.searchBarFixed = false)
        : (this.searchBarFixed = true);
    },
  },
};
</script>
<style lang="scss" scoped>
.err {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 8px;
}
</style>
